package com.tim.helper.analysis;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tim.ArgConstant;
import com.tim.util.SwaggerJsonUtil;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;

import java.io.File;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *@describe 解析swagger json；输出请求列表
 *@author Tim
 *@create 2022/9/20 9:24
 */
public class SwaggerAnalysis {
    /*
     * 每日说
     * http://dev-xqxc-boss.dailytalks.cn/v2/api-docs  每日说总控
     * http://dev-swg-doc.dailytalks.cn/v2/api-docs?group=APP端  每日说app端
     * http://dev-xqxc-rider.dailytalks.cn/v2/api-docs  每日说骑手后台
     * http://dev-xqxc-merchant.dailytalks.cn/v2/api-docs  每日说商户后台
     * http://dev-xqxc-dance.dailytalks.cn/v2/api-docs  领舞
     *
     * 懒猪
     * http://devswg.lazipig.cn:81/v2/api-docs?group=APP(用户app/骑手app)共用接口
     * http://devswg.lazipig.cn:81/v2/api-docs?group=PC后台
     * http://devswg.lazipig.cn:81/v2/api-docs?group=企业用户导单系统
     * http://devswg.lazipig.cn:81/v2/api-docs?group=用户APP
     * http://devswg.lazipig.cn:81/v2/api-docs?group=骑手APP
     *
     * 猪耳朵
     * http://devswg.pig-ear.com:81/v2/api-docs?group=公共：商户APP、商户PC
     * http://devswg.pig-ear.com:81/v2/api-docs?group=商户APP
     * http://devswg.pig-ear.com:81/v2/api-docs?group=商户PC
     * http://devswg.pig-ear.com:81/v2/api-docs?group=总控后台PC
     * http://devswg.pig-ear.com:81/v2/api-docs?group=渠道商H5
     * http://devswg.pig-ear.com:81/v2/api-docs?group=饿了么聚石塔(塔内系统)
     *
     */
    String url = "http://devswg.lazipig.cn:81/v2/api-docs?group=骑手APP";
    String destDir = ArgConstant.PROJECT_PATH;
    @Test// 输出接口url、名称
    public void printSwaggerTree() throws Exception {
        if(url.contains("?")){
            // 参数url encode
            int index = url.indexOf("?")+1;
            String[] queryParamInfos = url.substring(index).split("=");
            StringBuilder builder = new StringBuilder();
            for(int i = 0; i < queryParamInfos.length; i++) {
                builder.append(URLEncoder.encode(queryParamInfos[i]))
                        .append("=")
                        .append(URLEncoder.encode(++i<queryParamInfos.length ? queryParamInfos[i] : ""));
            }
            url = url.substring(0, index)+ builder;
        }
        JSONObject json = SwaggerJsonUtil.getSwaggerJson(url);
        String title = json.getJSONObject("info").getString("title");
        if(StringUtils.isBlank(title) || "API文档".equals(title)){
            String[] split = url.split("group=");// 优先取group值
            title = split.length>1&&split[1].length()>0 ? URLDecoder.decode(split[1]) : "Swagger文档"+ RandomUtils.nextInt(10000);
        }
        String fileName = title.replaceAll("[\\\\/]","-") +".txt";

        /* step1，paths按tag分组为Map*/
        JSONObject paths = json.getJSONObject("paths");
        List<JSONObject> methodJsonList = new ArrayList<>();
        // 按tags分组。path：summary请求描述，tags归属分组
        for(String path : paths.keySet()) {
            JSONObject jObj = paths.getJSONObject(path);
            String reqMethod = jObj.keySet().toArray(new String[0])[0];
            // 设置reqMethod、path
            JSONObject mJson = jObj.getJSONObject(reqMethod);
            mJson.put("reqMethod", reqMethod);// url后缀+Using+请求方法
            mJson.put("path", path);// 请求路径
            mJson.put("tag", mJson.getJSONArray("tags").getString(0));// 归属tag
            methodJsonList.add(mJson);
        }
        Map<String, List<JSONObject>> tagMethodsMap = methodJsonList.stream().collect(Collectors.groupingBy(item->item.getString("tag")));

        /* step2，按tags拼接实现类，遍历输出*/
        StringBuilder builder = new StringBuilder();
        JSONArray tags = json.getJSONArray("tags");
        for(Object tag : tags) {
            JSONObject tagJsonObjecgt = (JSONObject) tag;
            String tagName = tagJsonObjecgt.getString("name");
            String className = tagJsonObjecgt.getString("description")
                    .replaceAll("\\s+", "");
            builder.append(tagName.trim())
                    .append(" ")
                    .append(className)
                    .append("\n");
            List<JSONObject> methodJsonObjects = tagMethodsMap.get(tagName);
            for(JSONObject methodJsonObject : methodJsonObjects){
                builder.append("\t")
                        .append(methodJsonObject.getString("summary").trim()) // 请求描述
                        .append("；")
                        .append(methodJsonObject.getString("reqMethod").toUpperCase())
                        .append(" ")
                        .append(methodJsonObject.getString("path"))
                        .append("\n");
            }
        }
//    	System.out.println(builder);
        System.out.println(destDir+fileName);
        Files.write(Paths.get(destDir, fileName), Arrays.asList(builder.toString()));
    }

    @Test
    public void multiPrint() throws Exception {
        destDir = destDir+"swagger/";
        File file = new File(destDir);
        if(!file.exists()){
            file.mkdirs();
        }
        String info =
                "http://devswg.lazipig.cn:81/v2/api-docs?group=APP(用户app/骑手app)共用接口\n"
                        + "http://dev-swg-doc.dailytalks.cn/v2/api-docs?group=APP端  每日说app端\n"
                        + "http://dev-xqxc-boss.dailytalks.cn/v2/api-docs  每日说总控\n"
                        + "http://dev-xqxc-rider.dailytalks.cn/v2/api-docs  每日说骑手后台\n"
                        + "http://dev-xqxc-merchant.dailytalks.cn/v2/api-docs  每日说商户后台\n"
                        + "http://dev-xqxc-dance.dailytalks.cn/v2/api-docs  领舞\n"
                        + "http://devswg.lazipig.cn:81/v2/api-docs?group=PC后台\n"
                        + "http://devswg.lazipig.cn:81/v2/api-docs?group=企业用户导单系统\n"
                        + "http://devswg.lazipig.cn:81/v2/api-docs?group=用户APP\n"
                        + "http://devswg.lazipig.cn:81/v2/api-docs?group=骑手APP\n"
                        + "http://devswg.pig-ear.com:81/v2/api-docs?group=公共：商户APP、商户PC\n"
                        + "http://devswg.pig-ear.com:81/v2/api-docs?group=商户APP\n"
                        + "http://devswg.pig-ear.com:81/v2/api-docs?group=商户PC\n"
                        + "http://devswg.pig-ear.com:81/v2/api-docs?group=总控后台PC\n"
                        + "http://devswg.pig-ear.com:81/v2/api-docs?group=渠道商H5\n"
                        + "http://devswg.pig-ear.com:81/v2/api-docs?group=饿了么聚石塔(塔内系统)";

        String[] strs = info.trim().split("\n");
        for(String str : strs){
            url = str.trim().split("\\s+")[0];
            printSwaggerTree();
        }
    }


}
